package com.example.petadopt.dao;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import com.example.petadopt.common.Result;
import com.example.petadopt.entity.Adopt;
import com.example.petadopt.entity.Pet;
import com.example.petadopt.utils.SqliteUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * 宠物数据访问对象
 */
@SuppressLint("Range")
public class PetDao {

    /**
     * 添加宠物
     */
    public static Result<Void> addPet(Pet pet) {
        if (pet == null || pet.getName() == null || pet.getBreed() == null) {
            return new Result<>(false, "宠物信息不完整", null);
        }

        ContentValues values = new ContentValues();
        values.put("name", pet.getName());
        values.put("gender", pet.getGender());
        values.put("age", pet.getAge());
        values.put("weight", pet.getWeight());
        values.put("address", pet.getAddress());
        values.put("breed", pet.getBreed());
        values.put("hair_color", pet.getHairColor());
        values.put("character", pet.getCharacter());
        values.put("hobby", pet.getHobby());
        values.put("health_status", listToString(pet.getHealthStatus()));
        values.put("image", pet.getImage());

        long i = SqliteUtils.getInstance().getWritableDatabase().insert("tb_pet", null, values);
        if (i > 0) {
            return new Result<>(true, "添加宠物成功", null);
        }
        return new Result<>(false, "添加宠物失败", null);
    }

    /**
     * 删除宠物
     */
    public static Result<Void> deletePet(Long petId) {
        if (petId == null) {
            return new Result<>(false, "宠物ID不能为空", null);
        }

        int rows = SqliteUtils.getInstance().getWritableDatabase().delete("tb_pet", "id=?", new String[]{String.valueOf(petId)});
        if (rows > 0) {
            return new Result<>(true, "删除宠物成功", null);
        }
        return new Result<>(false, "删除宠物失败，该宠物可能不存在", null);
    }

    /**
     * 更新宠物信息
     */
    public static Result<Void> updatePet(Pet pet) {
        if (pet == null || pet.getId() == null) {
            return new Result<>(false, "宠物信息不完整", null);
        }

        ContentValues values = new ContentValues();
        if (pet.getName() != null) values.put("name", pet.getName());
        if (pet.getGender() != null) values.put("gender", pet.getGender());
        if (pet.getAge() != null) values.put("age", pet.getAge());
        if (pet.getWeight() != null) values.put("weight", pet.getWeight());
        if (pet.getAddress() != null) values.put("address", pet.getAddress());
        if (pet.getBreed() != null) values.put("breed", pet.getBreed());
        if (pet.getHairColor() != null) values.put("hair_color", pet.getHairColor());
        if (pet.getCharacter() != null) values.put("character", pet.getCharacter());
        if (pet.getHobby() != null) values.put("hobby", pet.getHobby());
        if (pet.getHealthStatus() != null)
            values.put("health_status", listToString(pet.getHealthStatus()));
        if (pet.getImage() != null) values.put("image", pet.getImage());

        int rows = SqliteUtils.getInstance().getWritableDatabase().update("tb_pet", values, "id=?", new String[]{String.valueOf(pet.getId())});
        if (rows > 0) {
            return new Result<>(true, "更新宠物信息成功", null);
        }
        return new Result<>(false, "更新宠物信息失败，该宠物可能不存在", null);
    }

    /**
     * 查询所有宠物
     */
    public static Result<List<Pet>> getAllPets() {
        return getAllPets(null);
    }

    /**
     * 查询所有宠物（关联用户收藏状态）
     */
    public static Result<List<Pet>> getAllPets(Long userId) {
        List<Pet> petList = new ArrayList<>();
        Cursor cursor = SqliteUtils.getInstance().getReadableDatabase().query("tb_pet", null, null, null, null, null, "id DESC");
        while (cursor.moveToNext()) {
            Pet pet = cursorToPet(cursor);
            // 关联宠物领养状态
            setAdoptionInfo(pet);
            // 关联用户收藏状态
            if (userId != null) {
                setCollectionInfo(pet, userId);
            }
            petList.add(pet);
        }
        cursor.close();
        return new Result<>(true, "查询成功", petList);
    }

    /**
     * 根据ID查询宠物
     */
    public static Result<Pet> getPetById(Long petId) {
        return getPetById(petId, null);
    }

    /**
     * 根据ID查询宠物（关联用户收藏状态）
     */
    public static Result<Pet> getPetById(Long petId, Long userId) {
        if (petId == null) {
            return new Result<>(false, "宠物ID不能为空", null);
        }
        Cursor cursor = SqliteUtils.getInstance().getReadableDatabase().query("tb_pet", null, "id=?", new String[]{String.valueOf(petId)}, null, null, null);
        if (cursor.moveToNext()) {
            Pet pet = cursorToPet(cursor);
            // 关联宠物领养状态
            setAdoptionInfo(pet);
            // 关联用户收藏状态
            if (userId != null) {
                setCollectionInfo(pet, userId);
            }
            cursor.close();
            return new Result<>(true, "查询成功", pet);
        }
        cursor.close();
        return new Result<>(false, "宠物不存在", null);
    }

    /**
     * 根据关键字搜索宠物
     * 支持搜索宠物名称、品种、地址
     */
    public static Result<List<Pet>> searchPetsByKeyword(String keyword) {
        return searchPetsByKeyword(keyword, null);
    }

    /**
     * 根据关键字搜索宠物（关联用户收藏状态）
     * 支持搜索宠物名称、品种、地址
     */
    public static Result<List<Pet>> searchPetsByKeyword(String keyword, Long userId) {
        if (TextUtils.isEmpty(keyword)) {
            return getAllPets(userId);
        }

        List<Pet> petList = new ArrayList<>();
        StringBuilder whereClause = new StringBuilder();
        List<String> whereArgs = new ArrayList<>();

        whereClause.append("name LIKE ? OR breed LIKE ? OR address LIKE ?");
        String likeParam = "%" + keyword + "%";
        whereArgs.add(likeParam);
        whereArgs.add(likeParam);
        whereArgs.add(likeParam);

        String[] args = whereArgs.toArray(new String[0]);
        Cursor cursor = SqliteUtils.getInstance().getReadableDatabase().query(
                "tb_pet", null, whereClause.toString(), args, null, null, "id DESC");

        while (cursor.moveToNext()) {
            Pet pet = cursorToPet(cursor);
            // 关联宠物领养状态
            setAdoptionInfo(pet);
            // 关联用户收藏状态
            if (userId != null) {
                setCollectionInfo(pet, userId);
            }
            petList.add(pet);
        }
        cursor.close();
        return new Result<>(true, "查询成功", petList);
    }

    /**
     * 从JSON文件加载宠物数据
     */
    public static Result<List<Pet>> loadPetsFromAssets(InputStream inputStream) {
        List<Pet> petList = new ArrayList<>();
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            bufferedReader.close();

            JSONArray jsonArray = new JSONArray(stringBuilder.toString());
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                Pet pet = new Pet();
                pet.setId(jsonObject.getLong("id"));
                pet.setName(jsonObject.getString("name"));
                pet.setGender(jsonObject.getString("gender"));
                pet.setAge(jsonObject.getInt("age"));
                pet.setWeight(jsonObject.getDouble("weight"));
                pet.setAddress(jsonObject.getString("address"));
                pet.setBreed(jsonObject.getString("breed"));
                pet.setHairColor(jsonObject.getString("hairColor"));
                pet.setCharacter(jsonObject.getString("character"));
                pet.setHobby(jsonObject.getString("hobby"));

                JSONArray healthArray = jsonObject.getJSONArray("healthStatus");
                List<String> healthStatusList = new ArrayList<>();
                for (int j = 0; j < healthArray.length(); j++) {
                    healthStatusList.add(healthArray.getString(j));
                }
                pet.setHealthStatus(healthStatusList);
                pet.setImage(jsonObject.getString("image"));

                petList.add(pet);
            }
            return new Result<>(true, "加载宠物数据成功", petList);
        } catch (IOException | JSONException e) {
            e.printStackTrace();
            return new Result<>(false, "加载宠物数据失败: " + e.getMessage(), null);
        }
    }

    /**
     * 将JSON数据导入数据库
     */
    public static Result<Void> importPetsFromJson(List<Pet> petList) {
        if (petList == null || petList.isEmpty()) {
            return new Result<>(false, "宠物数据为空", null);
        }

        SqliteUtils.getInstance().getWritableDatabase().beginTransaction();
        try {
            for (Pet pet : petList) {
                ContentValues values = new ContentValues();
                values.put("id", pet.getId());
                values.put("name", pet.getName());
                values.put("gender", pet.getGender());
                values.put("age", pet.getAge());
                values.put("weight", pet.getWeight());
                values.put("address", pet.getAddress());
                values.put("breed", pet.getBreed());
                values.put("hair_color", pet.getHairColor());
                values.put("character", pet.getCharacter());
                values.put("hobby", pet.getHobby());
                values.put("health_status", listToString(pet.getHealthStatus()));
                values.put("image", pet.getImage());
                //插入或者更新数据
                SqliteUtils.getInstance().getWritableDatabase().insertWithOnConflict("tb_pet", null, values, SQLiteDatabase.CONFLICT_REPLACE);
            }
            SqliteUtils.getInstance().getWritableDatabase().setTransactionSuccessful();
            return new Result<>(true, "导入宠物数据成功", null);
        } finally {
            SqliteUtils.getInstance().getWritableDatabase().endTransaction();
        }
    }

    /**
     * 获取宠物总数
     */
    public static int getPetCount() {
        Cursor cursor = SqliteUtils.getInstance().getReadableDatabase().rawQuery("SELECT COUNT(*) FROM tb_pet", null);
        int count = 0;
        if (cursor.moveToFirst()) {
            count = cursor.getInt(0);
        }
        cursor.close();
        return count;
    }

    /**
     * 将List<String>转换为字符串存储
     */
    private static String listToString(List<String> list) {
        if (list == null || list.isEmpty()) {
            return "";
        }
        JSONArray jsonArray = new JSONArray();
        for (String item : list) {
            jsonArray.put(item);
        }
        return jsonArray.toString();
    }

    /**
     * 将字符串转换为List<String>
     */
    private static List<String> stringToList(String str) {
        List<String> list = new ArrayList<>();
        if (TextUtils.isEmpty(str)) {
            return list;
        }
        try {
            JSONArray jsonArray = new JSONArray(str);
            for (int i = 0; i < jsonArray.length(); i++) {
                list.add(jsonArray.getString(i));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 从Cursor提取Pet对象
     */
    private static Pet cursorToPet(Cursor cursor) {
        Pet pet = new Pet();
        pet.setId(cursor.getLong(cursor.getColumnIndex("id")));
        pet.setName(cursor.getString(cursor.getColumnIndex("name")));
        pet.setGender(cursor.getString(cursor.getColumnIndex("gender")));
        pet.setAge(cursor.getInt(cursor.getColumnIndex("age")));
        pet.setWeight(cursor.getDouble(cursor.getColumnIndex("weight")));
        pet.setAddress(cursor.getString(cursor.getColumnIndex("address")));
        pet.setBreed(cursor.getString(cursor.getColumnIndex("breed")));
        pet.setHairColor(cursor.getString(cursor.getColumnIndex("hair_color")));
        pet.setCharacter(cursor.getString(cursor.getColumnIndex("character")));
        pet.setHobby(cursor.getString(cursor.getColumnIndex("hobby")));
        pet.setHealthStatus(stringToList(cursor.getString(cursor.getColumnIndex("health_status"))));
        pet.setImage(cursor.getString(cursor.getColumnIndex("image")));

        // 默认值设置
        pet.setIsAdopted(false);
        pet.setIsCollected(false);
        
        return pet;
    }

    /**
     * 设置宠物领养信息
     */
    private static void setAdoptionInfo(Pet pet) {
        if (pet == null || pet.getId() == null) {
            return;
        }

        Result<Adopt> adoptResult = AdoptDao.getAdoptByPetId(pet.getId());
        if (adoptResult.isSuccess() && adoptResult.getData() != null) {
            pet.setIsAdopted(true);
            pet.setAdoptUserId(adoptResult.getData().getAdoptUserId());
        } else {
            pet.setIsAdopted(false);
            pet.setAdoptUserId(null);
        }
    }

    /**
     * 设置宠物收藏信息
     */
    private static void setCollectionInfo(Pet pet, Long userId) {
        if (pet == null || pet.getId() == null || userId == null) {
            return;
        }

        boolean isCollected = CollectDao.isCollected(userId, pet.getId());
        pet.setIsCollected(isCollected);
    }
} 